<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice Management</title>
    <style>
        /* General Reset */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Body Styling */
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f6f9;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #0059b3;
            margin-bottom: 20px;
        }

        .search-bar {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .search-bar input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .search-bar button {
            padding: 10px 20px;
            background-color: #0059b3;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .search-bar button:hover {
            background-color: #003f7f;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #0059b3;
            color: white;
        }

        .action-buttons {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }

        .action-buttons button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            color: white;
        }

        .generate-btn {
            background-color: #28a745;
        }

        .generate-btn:hover {
            background-color: #1e7e34;
        }

        .report-btn {
            background-color: #ffc107;
        }

        .report-btn:hover {
            background-color: #e0a800;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Invoice Management</h1>

        <div class="search-bar">
            <input type="text" id="searchInput" placeholder="Search by Invoice Number or Quote Number">
            <button onclick="searchInvoice()">Search</button>
        </div>

        <table id="invoiceTable">
            <thead>
                <tr>
                    <th>Invoice Number</th>
                    <th>Client Name</th>
                    <th>Quote Number</th>
                    <th>Date Issued</th>
                    <th>Subtotal</th>
                    <th>VAT</th>
                    <th>Total Amount</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="invoiceTableBody"></tbody>
        </table>

        <div class="action-buttons">
            <button class="generate-btn" onclick="generateInvoice()">Generate Invoice</button>
            <button class="report-btn" onclick="downloadReport()">Download Report</button>
        </div>
    </div>

    <script>
        async function searchInvoice() {
            const searchInput = document.getElementById('searchInput').value.trim();

            if (!searchInput) {
                alert('Please enter an Invoice Number or Quote Number.');
                return;
            }

            try {
                const response = await fetch(`/invoices?search=${searchInput}`);
                const invoices = await response.json();

                const tableBody = document.getElementById('invoiceTableBody');
                tableBody.innerHTML = '';

                if (invoices.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="8">No invoices found.</td></tr>';
                    return;
                }

                invoices.forEach(invoice => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${invoice.invoiceNumber}</td>
                        <td>${invoice.clientName}</td>
                        <td>${invoice.quoteNumber}</td>
                        <td>${invoice.dateIssued}</td>
                        <td>₦${invoice.subtotal.toFixed(2)}</td>
                        <td>₦${invoice.vat.toFixed(2)}</td>
                        <td>₦${invoice.totalAmount.toFixed(2)}</td>
                        <td>
                            <button onclick="printInvoice(${invoice.invoiceNumber})">Print</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } catch (error) {
                alert('Failed to fetch invoices.');
            }
        }

        async function generateInvoice() {
            const quoteNumber = prompt('Enter Quote Number to Generate an Invoice:');
            if (!quoteNumber) return;

            try {
                const response = await fetch(`/invoices`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ quoteNumber })
                });

                const result = await response.json();
                if (result.invoiceNumber) {
                    alert(`Invoice #${result.invoiceNumber} generated successfully!`);
                    searchInvoice();
                } else {
                    alert(result.error || 'Failed to generate invoice.');
                }
            } catch (error) {
                alert('Error generating invoice.');
            }
        }

        async function printInvoice(invoiceNumber) {
    try {
        const response = await fetch(`/invoices/${invoiceNumber}`);
        if (!response.ok) {
            alert('Failed to fetch invoice details.');
            return;
        }

        const invoice = await response.json();

        // Replace with appropriate field names from the backend
        const contact = invoice.contactPerson || "N/A";
        const email = invoice.clientEmail || "N/A";

        const itemRows = Array.isArray(invoice.items)
            ? invoice.items.map(item => `
               
			   <tr>
                <td>${item.description}</td>
                <td>${item.quantity}</td>
                <td>₦${item.unitPrice.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                <td>₦${item.totalPrice.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
            </tr>
			
			
            `).join("")
            : `<tr><td colspan="4">No items available.</td></tr>`;

        const invoiceHTML = `
            <html>
            <head>
                <title>Invoice</title>
                <style>
                    body { font-family: Arial, sans-serif; padding: 20px; }
                    .container { max-width: 700px; margin: auto; }
                    h1 { text-align: center; }
                    .company-info { text-align: center; margin-bottom: 20px; }
                    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                    th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
                    th { background-color: #0059b3; color: white; }
                </style>
            </head>
            <body>
                <div class="container">
                    <h1>Invoice</h1>
                    <div class="company-info">
                        <img src="/logo.png" alt="Jetlink Solutions Logo" style="max-width: 200px; height: auto; margin-bottom: 20px;">
                        <p>Block 115, Plot 18, Kuboye Street, Off New Market Road</p>
                        <p>Email: service.ng@jetlinkng.com | Phone: +2348086562891</p>
                    </div>
                    <p><strong>Invoice Number:</strong> ${invoice.invoiceNumber}</p>
                    <p><strong>Date Issued:</strong> ${invoice.dateIssued}</p>
                    <p><strong>Customer Name:</strong> ${invoice.clientName}</p>
                    <p><strong>Contact:</strong> ${contact}</p>
                    <p><strong>Email:</strong> ${email}</p>
					<p><strong>Bank Account:</strong> ${invoice.bankAccount || "Not Available"}</p>

                    <table>
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Unit Price</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${itemRows}
                        </tbody>
                    </table>
					
                  <div style="text-align: right;">
				  
                   <p><strong>Subtotal:</strong> ₦${invoice.subtotal.toLocaleString('en-US', { minimumFractionDigits: 2 })}</p>
                <p><strong>VAT:</strong> ₦${invoice.vat.toLocaleString('en-US', { minimumFractionDigits: 2 })}</p>
                <p><strong>Total:</strong> ₦${invoice.totalAmount.toLocaleString('en-US', { minimumFractionDigits: 2 })}</p>
					   					 
					 <div class="signature-section" style="display: flex; margin-top: 30px;">
					 
    <div class="signature-box" style="text-align: left; width: 100%;">
        <p>_________________________</p>
        <p>Jetlink Signature</p>
    </div>
    <div class="signature-box" style="text-align: right; width: 100%;">
        <p>_________________________</p>
        <p>Customer Signature</p>
    </div>
</div>

                    </div>
                </body>
                </html>
           
        `;

        const printWindow = window.open("", "_blank");
        printWindow.document.open();
        printWindow.document.write(invoiceHTML);
        printWindow.document.close();
        printWindow.print();
    } catch (error) {
        console.error('Error in printInvoice:', error);
        alert('Failed to print invoice.');
    }
}


        function downloadReport() {
            const rows = document.querySelectorAll('#invoiceTable tbody tr');
            if (!rows.length) {
                alert('No data available to export.');
                return;
            }

            let csvContent = 'Invoice Number,Client Name,Quote Number,Date Issued,Subtotal,VAT,Total Amount\n';

            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                csvContent += Array.from(cells).map(cell => cell.textContent).join(',') + '\n';
            });

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'invoice_report.csv';
            link.click();
        }

        // Fetch initial data
        searchInvoice();
    </script>
</body>
</html>
